#include "Memo.h"
#include <random>
#include <QIODevice>
#include <QFontMetrics>
#include <QDataStream>
#include <QTextDocument>
#include <QTextDocumentFragment>

Memo::Memo()
    : Meta()
{
}

Memo::Memo(uint32_t id)
    : Meta(id)
{
}

static QFont G_YAHEI_FONT("Microsoft YaHei UI", 10);
static int YaHeiFontHeight()
{
    static QFontMetrics fmtx(G_YAHEI_FONT);

    return fmtx.height();
}

void Memo::paint(QPaintDevice* pd, const QRect& rect) const
{
    QRect dst = rect;
    dst.adjust(0, 0, -30, 0);
    dst.setLeft(rect.left() + 25);

    QPainter painter(pd);
    painter.save();

    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
    painter.drawPixmap(rect.topLeft(), QPixmap(":/LxMemo/icons/memo_file.png").scaled(16, 16));
    painter.drawPixmap(rect.topRight() - QPoint(25, -5), QPixmap(":/LxMemo/icons/other.png"));

    if (_snapshot.isEmpty()) {
        painter.setPen(Qt::darkGray);
        painter.drawText(dst.left(), dst.top() + 24, "NEW MEMO");
    }
    else {
        int lineHight = YaHeiFontHeight();
        painter.setFont(G_YAHEI_FONT);

        for (int i = 0; i < _snapshot.size(); i++) {
            int dx = dst.left(),
                dy = dst.top() + i * lineHight + 8;

            painter.drawText(QRectF(dx, dy, dst.width(), lineHight), Qt::AlignLeft, _snapshot[i]);
        }
    }
    if (!_time.isEmpty()) {
        QFont font = painter.font();
        font.setPointSizeF(8);
        painter.setFont(font);
        painter.setPen(Qt::gray);
        painter.drawText(dst.left(), dst.bottom() - 6, _time);
    }

    painter.restore();
}
QSize Memo::sizeHint() const
{
    int count = _snapshot.size();
    count = std::max(2, count);
    int extra = _time.isEmpty() ? 24 : 30;
    int height = count * QFontMetrics(G_YAHEI_FONT).height() + extra + 2 * 5;

    return QSize(100, height);
}

void Memo::SetHtml(const QString& html)
{
    _html = html;
    auto doc = QTextDocumentFragment::fromHtml(_html);
    auto raw = doc.toPlainText();

    _snapshot.clear();

    int count = 0;
    int ind = 0;

    do
    {
        ind = raw.indexOf('\n', 0);
        if (ind == -1) {
            if (!raw.isEmpty())
                _snapshot << raw;

            break;
        }

        count++;
        _snapshot << (raw.left(ind));
        raw = raw.right(raw.length() - ind - 1);
    } while (count < 5 && ind != -1);
}

QString Memo::GetMarkdown() const
{
    auto doc = QTextDocumentFragment::fromHtml(_html);

    return doc.toPlainText();
}

void Memo::SetSnapshot(const QString& snapshot)
{
    if (!snapshot.isEmpty()) {
        _snapshot = snapshot.split('\n');
    }
}